#!/bin/bash

set -e

cd $(dirname $0) || ( echo "无法切换到脚本所在路径请检查权限" && exit 1 )

HOST_LIST_FILE='host_list.txt'
DEFAULT_USERNAME='root'
DEFAULT_PASSWORD='abc.123'
DEFAULT_PORT='7686'
DEFAULT_KEY_FILE="${HOME}/.ssh/id_ed25519"
DEFSULT_PUBKEY_FILE="${DEFAULT_KEY_FILE}.pub"

# 检查是否有默认密钥
if [ ! -e "${DEFSULT_PUBKEY_FILE}" ];then
    echo -e "----->> 公钥不存在，重新创建密钥对 !\n密钥对位置 ：${HOME}/.ssh/"
    ssh-keygen -t ed25519 -P "" -f "${DEFAULT_KEY_FILE}"
fi

# 检查是否有 sshpass 工具
if ! which sshpass &>/dev/null; then
    echo -e "----->> 缺少必要软件 ：sshpass !\n正在安装......"
    yum install -y sshpass
fi

# 计数器
total_count=0
success_count=0
failed_count=0
# 密钥分发阶段
while read -r line; do
    if echo "$line" |grep -Eq "^\s*#|^\s*$";then
        continue
    fi
    total_count=$(( total_count + 1 ))
    # 在主机记录中截取信息
    IPADDR=$(echo "${line}" |awk '{print $1}')
    PORT=$(echo "${line}" |awk '{print $2}')
    USERNAME=$(echo "${line}" |awk '{print $3}')
    PASSWORD=$(echo "${line}" |awk '{print $4}')
    # 判断信息是否存在，不存在复制默认值
    [ -z "${IPADDR}" ] && continue
    [ -z "${PORT}" ] && PORT="${DEFAULT_PORT}"
    [ -z "${USERNAME}" ] && USERNAME="${DEFAULT_USERNAME}"
    [ -z "${PASSWORD}" ] && PASSWORD="${DEFAULT_PASSWORD}"
    # 分发密钥
    if timeout 5s sshpass -p"${PASSWORD}" ssh-copy-id -i "${PUBKEY_FILE}" -o "StrictHostKeyChecking=no" -p "${PORT}" "${USERNAME}"@"${IPADDR}"; then
        echo -e "[\033[1;32m${IPADDR}"' --- OK --- remote-cmd(hostname) : '"$(ssh -p "${PORT}" "${USERNAME}"@"${IPADDR}" hostname </dev/null)\033[0m\n"
        success_count=$(( success_count + 1 ))
        continue
    fi
    failed_count=$(( failed_count + 1 ))
    echo -e "[\033[1;5;31m${IPADDR}"' --- FAILED\033[0m\n'
done<"${HOST_LIST_FILE}"

echo
echo -e "\033[1;37m  total : ${total_count}\033[0m"
echo -e "\033[1;32msuccess : ${success_count}\033[0m"
echo -e "\033[1;31m failed : ${failed_count}\033[0m\n"
